package com.teamsun.controller;

import com.alibaba.fastjson.JSONObject;
import com.teamsun.annotation.PrivateHandlerMethod;
import com.teamsun.entity.UserInfo;
import com.teamsun.system.ILoginService;
import com.teamsun.util.Constants;
import com.teamsun.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息管理
 */
@Controller
@RequestMapping("/rptTools/user")
public class UserController {

    @Autowired
    private ILoginService loginService;

    /**
     * 新增用户默认密码
     */
    private static final String DEFAULT_PASSWORD = "123456";

    /**
     * 用户管理页面跳转
     * @return
     */
    @RequestMapping("/userMgr")
    @PrivateHandlerMethod
    public String userMgr() {
        return "../WEB-INF/page/userCfg";
    }

    /**
     * 修改密码页面跳转
     * @return
     */
    @RequestMapping("/modifyPassword")
    @PrivateHandlerMethod
    public String modifyPasswd() {
        return "../WEB-INF/page/modifyPassword";
    }

    /**
     * 查询用户信息
     */
    @RequestMapping("/queryUserInfo")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject queryUserInfo(HttpServletRequest request, int page, int rows) {
        JSONObject jsonObject = new JSONObject();

        int startIndex = (page - 1) * rows + 1;
        int endIndex = page * rows;

        Map<String, Object> param = new HashMap<String, Object>();
        String userName = request.getParameter("userName");
        if(StringUtils.isNotBlank(userName)) {
            userName = userName.trim();
            param.put("userName", userName);
        }

        // 查询用户信息
        Map<String, Object> userInfo = loginService.queryUserInfo(param, startIndex, endIndex);

        jsonObject.put("rows", userInfo.get("rows"));
        jsonObject.put("total", userInfo.get("total"));
        return jsonObject;
    }

    /**
     * 删除用户信息
     */
    @RequestMapping("/deleteUser")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject deleteUser(HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();

        try {
            String userId = request.getParameter("userId");  // 用户ID

            // 删除用户信息
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("userId", userId);
            loginService.deleteUserInfo(param);

            jsonObject.put("status", "1");
        } catch (Exception e) {
            jsonObject.put("status", "0");
            jsonObject.put("errorMsg", "删除用户信息失败");
            e.printStackTrace();
        }

        return jsonObject;
    }

    /**
     * 新增用户信息
     */
    @RequestMapping("/addUserInfo")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject addUserInfo(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String errroMsg = "";
        try {
            String userId = request.getParameter("userId");  // 用户ID
            userId = userId.trim();
            String userName = request.getParameter("userName");  // 用户名称
            userName = userName.trim();

            // 查看用户ID是否重复
            List<UserInfo> userInfos = loginService.queryUserById(userId);
            if(userInfos != null && userInfos.size() > 0) {
                jsonObject.put("status", "0");
                jsonObject.put("errorMsg", "用户ID[" + userId + "]已经存在");
            } else {
                // 保存用户信息
                UserInfo userInfo = new UserInfo();
                userInfo.setUserId(userId);
                userInfo.setUserName(userName);
                userInfo.setPassword(MD5Util.md5LowerCase(DEFAULT_PASSWORD));
                userInfo.setAdmin(Constants.NO);
                loginService.addUserInfo(userInfo);

                jsonObject.put("status", "1");
            }
        } catch (Exception e) {
            errroMsg = "新增用户信息失败";
            jsonObject.put("status", "0");
            jsonObject.put("errorMsg", errroMsg);
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 修改用户信息
     * @param request
     * @return
     */
    @RequestMapping("/updateUserInfo")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject updateUserInfo(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String errroMsg = "";
        try {
            String userId = request.getParameter("userId");
            String userName = request.getParameter("userName");  // 系统名称
            userName = userName.trim();

            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userId);
            userInfo.setUserName(userName);
            loginService.updateUserInfo(userInfo);

            jsonObject.put("status", "1");
        } catch (Exception e) {
            errroMsg = "修改用户信息失败";
            jsonObject.put("status", "0");
            jsonObject.put("errorMsg", errroMsg);
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 重置用户密码
     * @param request
     * @return
     */
    @RequestMapping("/resetPassword")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject resetPassword(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String errroMsg = "";
        try {
            String userId = request.getParameter("userId");
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userId);
            userInfo.setPassword(MD5Util.md5LowerCase(DEFAULT_PASSWORD));

            // 修改用户密码
            loginService.updateUserPassword(userInfo);

            jsonObject.put("status", "1");
        } catch (Exception e) {
            errroMsg = "重置用户密码失败";
            jsonObject.put("status", "0");
            jsonObject.put("errorMsg", errroMsg);
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 修改用户密码
     * @param request
     * @return
     */
    @RequestMapping("/updatePassword")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject updatePassword(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String errroMsg = "";
        try {
            String oldPasswd = request.getParameter("oldPasswd");
            String newPasswd = request.getParameter("newPasswd");
            String confirmPasswd = request.getParameter("confirmPasswd");

            UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constants.SESSION_USER);
            String userId = userInfo.getUserId();
            String passwd = userInfo.getPassword();
            oldPasswd = MD5Util.md5LowerCase(oldPasswd);
            if(!oldPasswd.equals(passwd)) {
                jsonObject.put("status", "0");
                jsonObject.put("errorMsg", "原密码输入错误");
                return jsonObject;
            }
            if(!newPasswd.equals(confirmPasswd)) {
                jsonObject.put("status", "0");
                jsonObject.put("errorMsg", "新密码和确认密码不一致");
                return jsonObject;
            }
            UserInfo updateInfo = new UserInfo();
            updateInfo.setUserId(userId);
            updateInfo.setPassword(MD5Util.md5LowerCase(newPasswd));

            // 修改用户密码
            loginService.updateUserPassword(updateInfo);
            // 保证Session中的密码信息一致
            userInfo.setPassword(MD5Util.md5LowerCase(newPasswd));

            jsonObject.put("status", "1");
        } catch (Exception e) {
            errroMsg = "修改用户密码失败";
            jsonObject.put("status", "0");
            jsonObject.put("errorMsg", errroMsg);
            e.printStackTrace();
        }
        return jsonObject;
    }
}
